const WebSocketServer = require('ws')
const port = 7777;
const server = new WebSocketServer.Server({port})
const K = 'abcedefghijklmnopqrstuvwxyz0123456789'
const N = '操你大爷赵日天装逼牛批还有谁一个能打的都没有小奶狗';
const H = [
    'https://q3.itc.cn/q_70/images03/20240309/6620f2254c4c4d1eb2f3134092fac466.jpeg',
    'https://q4.itc.cn/q_70/images03/20240403/522200e4ebed4f3caf9f3eaea7ba647e.jpeg',
    'https://q5.itc.cn/q_70/images03/20240331/90002c03e8334d9ea30de98790831762.jpeg',
    'https://q9.itc.cn/q_70/images03/20240331/4eb78ba09c344ecfad73886b7db868dc.jpeg',
    'https://q2.itc.cn/q_70/images03/20240312/c1da57f8000e428eabcb5effb868c5dd.jpeg',
    'https://q1.itc.cn/q_70/images03/20240320/fcf023d835c54f78bac6c7efc98fbb4c.jpeg',
    'https://q4.itc.cn/q_70/images03/20240405/0fe4005840664f30b76f1a63909a5489.jpeg',
    'https://q2.itc.cn/q_70/images03/20240312/519714591a8241b884f21e37b54d4319.jpeg',
    'https://q4.itc.cn/q_70/images03/20240405/39ec09deda3a41d79e03897b0fdf68a0.jpeg',
    'https://img0.baidu.com/it/u=3383294599,716789071&fm=253&fmt=auto&app=120&f=JPEG?w=501&h=500',
    'https://q3.itc.cn/q_70/images03/20240309/6620f2254c4c4d1eb2f3134092fac466.jpeg',
]
function genSession(n) {
    let s = '';
    n = n || 16
    for(let i = 0; i < n; i++) {
        s += K[Math.random() * K.length | 0]
    }
    return s;
}

function genName() {
    let s = ''
    let n = Math.random() * 3 + 2
    for(let i = 0; i < n; i++) {
        s += N[Math.random() * N.length | 0]
    }
    return s
}

function genUserInfo() {
    return {
        id: genSession(),
        userHead: H[Math.random() * H.length | 0],
        name: genName()
    }
}

server.on('connection', ws => {
    const userInfo = genUserInfo()
    ws.userInfo = userInfo
    ws.send(JSON.stringify({type:'user_info', userInfo}))
    sendUserList()
    ws.on('message', data => {
        data = JSON.parse(data)
        if(data.to) {
            data.from = userInfo.id
            sendTo(data.to, data)
        } else {
            data.from = userInfo.id
            sendOther(userInfo.id, data)
        }
    })
    ws.on('close', () => {
        sendUserList()
    })
})

function sendTo(id, data) {
    for(let ws of server.clients.values()) {
        if(ws.userInfo.id === id) {
            ws.send(JSON.stringify(data))
            break
        }
    }
}

function sendOther(id, data) {
    for(let ws of server.clients.values()) {
        if(ws.userInfo.id !== id) {
            ws.send(JSON.stringify(data))
        }
    }
}

function sendUserList() {
    const list = []
    for(let ws of server.clients.values()) {
        list.push(ws.userInfo)
    }
    server.clients.forEach(ws => {
        const data = list.filter(v => v.id !== ws.userInfo.id)
        ws.send(JSON.stringify({type: 'user_list', result: data}))
    })
}

function broadCast(data) {
    server.clients.forEach(client => {
        client.send(JSON.stringify(data))
    })
}